<template>
	<view class="box">
		<u-tabbar
			:zIndex="99"
			:value="currentTabbarIndex"
			:border="false"
			@change="onChange"
			activeColor="#FC2422"
		>
			<u-tabbar-item 
			v-for="(item,index) in tarbarList"
			:key="index"
			:text="item.font">
				<image
					class="icon"
					slot="active-icon"
					:src="pathUrl + item.image_url_active"
				></image>
				<image
					class="icon"
					slot="inactive-icon"
					:src="pathUrl + item.image_url"
				></image>
			</u-tabbar-item>
		</u-tabbar>
	</view>
</template>

<script>
	import {getIndexApi} from '@/api/index.js'
	import {mapState} from 'vuex'
	export default {
		computed: {
			...mapState(['currentTabbarIndex','tabbar','hasLogin'])
		},
		data() {
			return {
				tarbarList: [],
				currentIndex: 0,
				pathUrl: this.$pathUrl
			}
		},
		created() {
			if(this.tabbar.length > 0) {
				this.tarbarList = this.tabbar
				return
			}
			this.getIndexData()
		},
		methods: {
			// 获取tabbar数据
			async getIndexData() {
				const res = await getIndexApi()
				const {tabbar = []} = res.data
				this.tarbarList = tabbar
				this.$store.commit('SET_TABBAR',tabbar)
			},
			// tabbar
			onChange(index) {
				let path = ''
				let isLogin = false
				switch(index) {
					case 0:
					path = '/pages/index/index'
					break;
					case 1:
					path = '/pages/seeding/seeding'
					break;
					case 2:
					path = '/pages/category/category'
					break;
					case 3:
					path = '/pages/cart/cart'
					break;
					case 4:
					path = '/pages/my/my'
					isLogin = true
					break;
				}
				if(isLogin) {
					if(!this.hasLogin) {
						uni.showToast({
							title: '请先登录!',
							icon: 'none'
						})
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/login/login',
								animationType: 'fade-in'
							})
						},500)
						return
					}
				}
				this.$store.commit('SET_TABBAR_INDEX',index)
				uni.switchTab({
					url: path
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.box {
		position: relative;
	}
	.icon {
		width: 24px;
		height: 24px;
	}
	
</style>
